package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:zhq
 * @Date: 2025/09/17 16:57
 * @Description:
 */
@Service
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {


    @Resource
    private AgencyCertificationMapper agencyCertificationMapper;
    @Resource
    private IServeProviderService serveProviderService;
    /**
     * 分页查询
     *
     * @param agencyCertificationAuditPageQueryReqDTO
     */
    @Override
    public PageResult<AgencyCertificationAudit> pageQuery(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        //分页查询
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(agencyCertificationAuditPageQueryReqDTO, AgencyCertificationAudit.class);

        //添加查询条件
        lambdaQuery().eq(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getAuditStatus()), AgencyCertificationAudit::getAuditStatus, agencyCertificationAuditPageQueryReqDTO.getAuditStatus())
                .eq(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getCertificationStatus()), AgencyCertificationAudit::getCertificationStatus, agencyCertificationAuditPageQueryReqDTO.getCertificationStatus())
                .like(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getName()), AgencyCertificationAudit::getName, agencyCertificationAuditPageQueryReqDTO.getName())
                .eq(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getLegalPersonName()), AgencyCertificationAudit::getIdNumber, agencyCertificationAuditPageQueryReqDTO.getLegalPersonName())
                .page(page);
        //按照条件排序
        if (ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getOrderBy1())) {
            page.addOrder(new OrderItem(agencyCertificationAuditPageQueryReqDTO.getOrderBy1(), agencyCertificationAuditPageQueryReqDTO.getIsAsc1()));
        }
        if (ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getOrderBy2())) {
            page.addOrder(new OrderItem(agencyCertificationAuditPageQueryReqDTO.getOrderBy2(), agencyCertificationAuditPageQueryReqDTO.getIsAsc2()));
        }
        PageResult<AgencyCertificationAudit> pageResult = new PageResult<>();
        pageResult.setPages(page.getPages());
        pageResult.setTotal(page.getTotal());
        pageResult.setList(page.getRecords());
        return pageResult;
    }

    /**
     * 机构认证审核
     *
     * @param certificationAuditReqDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void auditCertification(String id, CertificationAuditReqDTO certificationAuditReqDTO) {
        //根据id查询认证申请
        AgencyCertificationAudit agencyCertificationAudit = baseMapper.selectById(id);
        if (agencyCertificationAudit == null) {
            throw new RuntimeException("认证申请不存在");
        }
        //更新认证审核表
        agencyCertificationAudit.setAuditStatus(1);
        agencyCertificationAudit.setCertificationStatus(certificationAuditReqDTO.getCertificationStatus());
        agencyCertificationAudit.setRejectReason(certificationAuditReqDTO.getRejectReason());
        agencyCertificationAudit.setAuditorName(UserContext.getCurrentUser().getName());
        agencyCertificationAudit.setAuditorId(UserContext.currentUserId());
        agencyCertificationAudit.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(agencyCertificationAudit);
        //更新服务人员认证信息表
        agencyCertificationMapper.update(null,new LambdaUpdateWrapper<AgencyCertification>()
                .eq(AgencyCertification::getId,agencyCertificationAudit.getServeProviderId())
                .set(AgencyCertification::getCertificationStatus,certificationAuditReqDTO.getCertificationStatus())
                .set(AgencyCertification::getCertificationTime,LocalDateTime.now())
                .set(AgencyCertification::getUpdateTime,LocalDateTime.now())
        );

        if (certificationAuditReqDTO.getCertificationStatus() == 2) {
            //认证成功，更新服务人员表
            serveProviderService.update(new LambdaUpdateWrapper<ServeProvider>()
                            .eq(ServeProvider::getId,agencyCertificationAudit.getServeProviderId())
                    .set(ServeProvider::getSettingsStatus,1)
            );
        }
    }

    @Override
    public RejectReasonResDTO rejectReason() {
        Long id = UserContext.currentUserId();
        AgencyCertificationAudit one = this.lambdaQuery().eq(AgencyCertificationAudit::getServeProviderId, id).one();
        return one.getRejectReason() == null ?  new RejectReasonResDTO(""): new RejectReasonResDTO(one.getRejectReason());
    }

    /**
     * 实名认证
     *
     * @param agencyCertificationAuditAddReqDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void realNameAuthentication(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        //检查机构是否注册
        List<AgencyCertificationAudit> list = this.lambdaQuery().eq(AgencyCertificationAudit::getIdNumber, agencyCertificationAuditAddReqDTO.getIdNumber())
                .eq(AgencyCertificationAudit::getLegalPersonIdCardNo, agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo())
                .list();
        if (CollUtil.isNotEmpty(list)){
            throw new RuntimeException("该机构已经注册");
        }
        //添加认证审核申请
        AgencyCertificationAudit newAgency = BeanUtils.copyBean(agencyCertificationAuditAddReqDTO, AgencyCertificationAudit.class);
        newAgency.setAuditStatus(CertificationStatusEnum.INIT.getStatus());
        newAgency.setCreateTime(LocalDateTime.now());
        newAgency.setCertificationStatus(1);
        newAgency.setServeProviderId(UserContext.currentUserId());
        baseMapper.insert(newAgency);
        //添加认证信息
        AgencyCertification agencyCertification = BeanUtil.copyProperties(newAgency, AgencyCertification.class);
        agencyCertification.setId(newAgency.getServeProviderId());
        agencyCertification.setCertificationTime(LocalDateTime.now());
        agencyCertification.setCertificationStatus(1);
        agencyCertification.setCreateTime(LocalDateTime.now());
        agencyCertificationMapper.insert(agencyCertification);
    }
}
